<template>
    <Modal v-model:visible="isShowModal" title="编辑成员" @ok="handleOk" @cancel="handleCancel" ok-text="提交"
        cancel-text="取消" :loading="loading">
        <Form :model="formState" ref="formRef" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }" :rules="rules">
            <FormItem label="姓名" name="name">
                <Input v-model:value="formState.name" placeholder="请输入姓名" allowClear></Input>
            </FormItem>
            <FormItem label="手机号" name="mobile">
                <Input v-model:value="formState.mobile" placeholder="请输入手机号" allowClear></Input>
            </FormItem>
            <FormItem label="部门" name="departmentId">
                <Select v-model:value="formState.departmentId" style="width: 100%" placeholder="请选择部门"
                    option-label-prop="children" allowClear @change="handleDepartment">
                    <Option :value="item.departmentId" :key="item.departmentId" v-for="item in departmentOption">
                        {{ item.departmentName }}
                    </Option>
                </Select>
            </FormItem>
            <FormItem label="岗位" name="jobId">
                <Select v-model:value="formState.jobId" placeholder="请选择岗位" allowClear>
                    <Option :value="item.jobId" :key="item.jobId" v-for="item in positionOption">
                        {{ item.jobName }}
                    </Option>
                </Select>
            </FormItem>
            <FormItem label="职位名称" name="position">
                <Input v-model:value="formState.position" placeholder="请输入职位名称" allowClear></Input>
            </FormItem>
            <FormItem label="是否超管" name="isAdmin">
                <RadioGroup v-model:value="formState.isAdmin" :options="EnumIsAdminUser" />
            </FormItem>
        </Form>
    </Modal>
</template>

<script lang="ts" setup>
import { Modal, Form, Input, message, Select, RadioGroup } from 'ant-design-vue'
import { Rule } from 'ant-design-vue/es/form';
import { EnumIsAdminUser } from './index'
import { CompanyApi, CompanyUserAddRequest, CompanyUserApi, UserRegistrationCompanyUserResult } from '@/api';

const FormItem = Form.Item;
const Option = Select.Option;

const emit = defineEmits(['ok']);

const isShowModal = ref(false)
const loading = ref(false)
const companyId = ref();
const userId = ref();
const companyUserId = ref()
const formState = ref<CompanyUserAddRequest>({
    name: '',
    mobile: '',
})
const formRef = ref()
const rules: Record<string, Rule[]> = {
    name: [{ required: true, message: "请输入姓名", trigger: 'blur' }],
    mobile: [{ required: true, message: "请输入手机号", trigger: 'blur' }],
};
const departmentOption = ref()
const positionOption = ref();

const handleOpen = (id: any, data: UserRegistrationCompanyUserResult) => {
    handleEmpty();

    userId.value = id;
    companyId.value = data.company!.id;
    companyUserId.value = data.user!.id;
    formState.value = {
        name: data.user!.name || '',
        mobile: data.user!.mobile || '',
        departmentId: data.user!.departmentId,
        jobId: data.user!.jobId,
        position: data.user!.position,
        isAdmin: data.user!.isAdmin,
    };
    getDarpmentOption();
    isShowModal.value = true;
}

const handleOk = () => {
    loading.value = true;
    formRef.value
        .validate()
        .then(async () => {
            if (userId.value) {
                await CompanyUserApi.companyuserUserupdate(companyUserId.value, formState.value)
                message.success('修改成功')
                emit('ok')
                handleClose(); // 关闭弹窗
            }
        })
        .catch((err: any) => {
            console.log('校验失败', err);
        }).finally(() => {
            loading.value = false;
        });
}

const handleEmpty = () => {
    companyId.value = undefined
    formState.value = {
        name: '',
        mobile: '',
    };
}

function handleClose(){
    isShowModal.value = false;
}

function handleCancel(){
    handleEmpty();
    handleClose();
}


// 获取部门岗位二级列表
async function getDarpmentOption() {
    let res = await CompanyApi.companyGetdepartmentjobs(companyId.value);
    departmentOption.value = res;

    if (formState.value.departmentId) {
        let curDepartment = res.find(v => v.departmentId === formState.value.departmentId)?.jobs;
        positionOption.value = curDepartment;
    }
}

// 部门选择
function handleDepartment(id: any) {
    positionOption.value = departmentOption.value.filter((v: any) => v.departmentId === id)[0].jobs
    formState.value.jobId = undefined;
}
defineExpose({ handleOpen })
</script>